import 'package:flutter/cupertino.dart';
import 'package:rxdart/rxdart.dart';
import 'package:schoollifedemo/base/common_function.dart';
import 'package:schoollifedemo/base/routers.dart';
import 'package:schoollifedemo/base/url_contract.dart';
import 'package:schoollifedemo/commonwidget/common_base_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class HomePageViewModel extends BaseViewModel {
  FriendCircleMessageResponse? _messageResponse;

  FriendCircleMessageResponse? get messageResp => _messageResponse;

  WeatherCommonResponse? _weatherCommonResponse;

  WeatherCommonResponse? get weatherResp => _weatherCommonResponse;

  PublishSubject loadingState = PublishSubject<CommonLoadingState?>();

  // 转到编辑朋友圈页面
  Future<void> turnToEditFriendCirclePage(BuildContext context) async {
    await getApplication()
        .routerNavigateTo(context, RoutersPath.editFriendCirclePage);
  }

  // 发布评论
  Future<void> publishCommit({
    required String commit, // 评论内容
    String? timestamps, // 评论时间
    String? commitWho, // 评论谁
    required String whoCommit, // 评论人
  }) async {}

  // 拉取最新的天气消息
  Future<void> pullLatestWeather({
    OnSuccess? onSuccess, // 成功回调
    OnFailure? onFailure, // 失败回调
  }) async {
    final params = <String, Object>{};
    params['city_code'] = (getCityCode());
    final result = await getNetworkUtil().postHttp(
      UrlContract.pullWeatherReport,
      params: params,
    );
    final resp = WeatherCommonResponse.fromMap(result);
    if (resp.status == 0) {
      _weatherCommonResponse = resp;
      if (onSuccess != null) {
        onSuccess();
      }
    } else {
      if (onFailure != null) {
        onFailure(resp.msg);
      }
    }
  }

  String getCityCode() {
    String? cityCode = '';
    return cityCode;
  }

  // 拉取最新的朋友圈消息
  Future<void> pullFriendCircleMessageList({
    int currentPage = 1, // 当前的页面
    int pageSize = 10, // 每页数量
    bool append = false, // 是否是追加
    bool refreshQuickly = false,
    OnSuccess? onSuccess, // 成功回调
    OnFailure? onFailure, // 失败回调
  }) async {
    // 没有更多的时候，不操作
    if (!refreshQuickly) {
      if (_messageResponse?.haveMore == false) {
        return;
      }
    }
    final params = <String, Object>{};
    params['account'] = getApplication().getLoginAccount() ?? '';
    params['current_page'] = currentPage;
    params['page_size'] = pageSize;
    final result = await getNetworkUtil().postHttp(
      UrlContract.pullAllFriendCircleList,
      params: params,
    );
    final resp = FriendCircleMessageResponse.fromMap(result);
    if (resp.status == 0) {
      if (append) {
        resp.messageList?.forEach((element) {
          _messageResponse?.messageList?.add(element);
        });
        _messageResponse?.haveMore = resp.haveMore;
        _messageResponse?.status = resp.status;
        _messageResponse?.msg = resp.msg;
        _messageResponse?.currentPage = resp.currentPage;
      } else {
        _messageResponse = resp;
      }
      if (onSuccess != null) {
        onSuccess();
      }
      loadingState.add(CommonLoadingState.successTypeOne);
    } else {
      if (onFailure != null) {
        onFailure(resp.msg);
      }
      loadingState.add(CommonLoadingState.failure);
    }
  }

  void onLove(BuildContext context, int index) async {
    final params = <String, Object>{};
    params['account'] = getApplication().getLoginAccount() ?? '';
    params['conversation_id'] =
        _messageResponse?.messageList?[index].conversationId ?? '';
    final result = await getNetworkUtil().postHttp(
      UrlContract.loveFriendCircleItem,
      params: params,
    );
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      _messageResponse?.messageList?[index].isLove = true;
      _messageResponse?.messageList?[index].loveCount =
          (_messageResponse?.messageList?[index].loveCount ?? 0) + 1;
      loadingState.add(CommonLoadingState.successTypeOne);
    } else {
      DialogUtils.showTitleAndMessageDialog(
        context,
        clickOutSideDismiss: true,
        title: '错误',
        msg: 'resp error in home page viewmodel: ${resp.msg}',
      );
    }
  }

  void onUnLove(BuildContext context, int index) async {
    final params = <String, Object>{};
    params['account'] = getApplication().getLoginAccount() ?? '';
    params['conversation_id'] =
        _messageResponse?.messageList?[index].conversationId ?? '';
    final result = await getNetworkUtil().postHttp(
      UrlContract.unLoveFriendCircleItem,
      params: params,
    );
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      _messageResponse?.messageList?[index].isLove = false;
      _messageResponse?.messageList?[index].loveCount =
          (_messageResponse?.messageList?[index].loveCount ?? 1) - 1;
      loadingState.add(CommonLoadingState.successTypeOne);
    } else {
      DialogUtils.showTitleAndMessageDialog(
        context,
        clickOutSideDismiss: true,
        title: '错误',
        msg: 'resp error in home page viewmodel: ${resp.msg}',
      );
    }
  }

  // 评论朋友圈
  Future<void> commitFriendCircleItem({
    required String conversationId,
    required String msg,
    OnSuccess? onSuccess, // 成功回调
    OnFailure? onFailure, // 失败回调
  }) async {
    final params = <String, Object>{};
    params['account'] = getApplication().getLoginAccount() ?? '';
    params['conversation_id'] = conversationId;
    params['msg'] = msg;
    params['timestamps'] = DateTime.now().millisecondsSinceEpoch.toString();
    final result = await getNetworkUtil()
        .postHttp(UrlContract.commitFriendCircleItem, params: params);
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      if (onSuccess != null) {
        onSuccess();
      }
    } else {
      if (onFailure != null) {
        onFailure(resp.msg);
      }
    }
  }

  void onCommit(BuildContext context, int index) {
    String lastText = '';
    bool isEdit = false;
    // 弹出编辑评论窗口进行评论
    DialogUtils.showEditCommitDialog(
      context,
      onBackClick: () async {
        if (!isEdit) {
          Navigator.pop(context);
        } else {
          bool? trueOrFalse = await DialogUtils.showCancelAndConfirmDialog(
            context,
            title: '询问',
            msg: '已编辑，是否返回？',
          );
          if (trueOrFalse == true) {
            Navigator.pop(context);
          }
        }
      },
      onCancelClick: () async {
        if (!isEdit) {
          Navigator.pop(context);
        } else {
          bool? trueOrFalse = await DialogUtils.showCancelAndConfirmDialog(
            context,
            title: '询问',
            msg: '已编辑，是否返回？',
          );
          if (trueOrFalse == true) {
            Navigator.pop(context);
          }
        }
      },
      onConfirmClick: () async {
        commitFriendCircleItem(
          conversationId:
              _messageResponse?.messageList?[index].conversationId ?? '',
          msg: lastText,
          onFailure: (msg) {
            DialogUtils.showTitleAndMessageDialog(
              context,
              clickOutSideDismiss: true,
              title: '错误',
              msg: 'resp error in home page viewmodel: $msg',
            );
          },
          onSuccess: () async {
            // 获取评论列表
            final conversationId =
                _messageResponse?.messageList?[index].conversationId;
            _messageResponse?.messageList?[index].commitList =
                await getCommitList(conversationId ?? '');
            loadingState.add(CommonLoadingState.successTypeOne);
            Navigator.pop(context);
          },
        );
      },
      onTextChange: (text) {
        if (lastText != text) {
          lastText = text;
          isEdit = true;
        }
      },
    );
  }

  // 拉取个人信息
  Future<void> pullPersonalInfo(
    String? account, {
    OnSuccessWithValue? onSuccess,
    OnFailure? onFailure,
  }) async {
    final params = <String, Object>{};
    params['account'] = account ?? '';
    Map<String, dynamic>? json = await getNetworkUtil().postHttp(
      UrlContract.pullPersonalInfo,
      params: params,
    );
    final resp = PersonalInfoResponse.fromMap(json);
    if (resp.status == 0) {
      if (onSuccess != null) {
        onSuccess(resp);
      }
    } else {
      if (onFailure != null) {
        final commonResp = CommonResponse.fromMap(json);
        onFailure(commonResp.msg);
      }
    }
  }

  // 获取评论列表
  Future<List<FriendCircleCommit?>?> getCommitList(
      String conversationId) async {
    final params = <String, Object>{};
    params['conversation_id'] = conversationId;
    final result = await getNetworkUtil()
        .postHttp(UrlContract.pullConversationCommit, params: params);

    final resp = FriendCircleCommitResponse.fromMap(result);

    if (resp.status == 0) {
      return resp.commitList;
    } else {
      return null;
    }
  }

  // 删除评论内容
  Future<bool?> deleteCommit({
    required String conversationId,
    required String commitId,
  }) async {
    final params = <String, Object>{};
    params['conversation_id'] = conversationId;
    params['commit_id'] = commitId;
    final result = await getNetworkUtil()
        .postHttp(UrlContract.deleteFriendCircleItemCommit, params: params);
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      return resp.trueOrFalse;
    } else {
      return null;
    }
  }

  // 评论他人内容
  Future<bool?> commitToWhoCommit({
    required String conversationId,
    required String toWho,
    required String msg,
    OnSuccess? onSuccess, // 成功回调
    OnFailure? onFailure, // 失败回调
  }) async {
    final params = <String, Object>{};
    params['account'] = getApplication().getLoginAccount() ?? '';
    params['conversation_id'] = conversationId;
    params['msg'] = msg;
    params['timestamps'] = DateTime.now().millisecondsSinceEpoch.toString();
    final result = await getNetworkUtil()
        .postHttp(UrlContract.commitFriendCircleItemToWho, params: params);
    final resp = CommonResponse.fromMap(result);
    if (resp.status == 0) {
      if (onSuccess != null) {
        onSuccess();
      }
    } else {
      if (onFailure != null) {
        onFailure(resp.msg);
      }
    }
  }
}
